package cn.chanel.mall.admin.aspect;
import cn.chanel.mall.admin.conf.AdminAccountConfig;
import cn.chanel.mall.admin.expection.AdminException;
import cn.chanel.mall.constant.CookieName;
import cn.chanel.mall.enums.ResultEnum;
import cn.chanel.mall.exception.MallException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


/**
 * 管理员操作拦截器
 */
@Slf4j
@Aspect
@Component
public class AdminLoginAspect {
    @Resource
    private AdminAccountConfig adminAccountConfig;

    @Before("execution(public * cn.chanel.mall.admin.controller.*.*(..))" +
            "&& !execution(public * cn.chanel.mall.admin.controller.AdminLoginController.*(..))")
    public void isAdmin() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert requestAttributes != null;
        final int hashCode = adminAccountConfig.getUsername().hashCode();
        HttpServletRequest request = requestAttributes.getRequest();
        final HttpSession session = request.getSession();
        if(session.getId() != null){
            Object hashCodeO = session.getAttribute(CookieName.ADMIN_LOGIN);
            if(hashCodeO != null && hashCodeO.equals(hashCode)){
                return;
            }
        }
        throw new AdminException(ResultEnum.NEED_ADMIN_LOGIN);
    }
}
